package com.base.mine;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.utils.TimePickUtil;
import com.base.commonlib.widget.AnimUtil;
import com.base.commonlib.widget.KeyboardWatcher;
import com.base.commonlib.widget.PhotoSelectManager;
import com.base.mine.databinding.ActivityCenterintroBinding;
import com.base.mine.presenter.CenterIntroPresenter;
import com.base.mine.view.CenterIntroView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

/**
 * 个人中心
 * Created by weikailiang on 2020/3/18.
 */
@Route(path = "/mine/centerintro")
public class CenterIntroActivity extends CBaseBarMvpActivity<CenterIntroPresenter> implements CenterIntroView,KeyboardWatcher.SoftKeyboardStateListener {

    private static final int CAMERA_RESULT = 100;
    private static final int PHOTO_CUT = 102;
    private ActivityCenterintroBinding mBinding;
    private static final int PHOTO_RESULT = 101;
    private KeyboardWatcher keyboardWatcher;
    private float scale = 0.8f;
    @Override
    protected int getLayoutResource() {
        return R.layout.activity_centerintro;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityCenterintroBinding) mRootBinding;
        mPresenter = new CenterIntroPresenter(this, this);
        mPresenter.start();
        setBackNavigation();
        setBarTitle("个人中心");
        setRigImg(R.drawable.ic_title_save, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMes("开发中");
            }
        });

    }

    @Override
    protected void start() {
        mBinding.personInformationCamares.setImageResource(R.drawable.ic_empty);
        mBinding.personInformationCamares.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PhotoSelectManager.getmInstance().show(CenterIntroActivity.this, new PhotoSelectManager.popListener() {
                    @Override
                    public void cameraClick(TextView camera) {
                        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(in, CAMERA_RESULT);
                        PhotoSelectManager.getmInstance().dismiss();
                    }

                    @Override
                    public void albumClick(TextView photos) {
                        Intent in = new Intent(Intent.ACTION_PICK);
                        in.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(in, PHOTO_RESULT);
                        PhotoSelectManager.getmInstance().dismiss();
                    }

                    @Override
                    public void cancelClick(TextView cacel) {
                        PhotoSelectManager.getmInstance().dismiss();
                    }
                });
            }
        });
        keyboardWatcher = new KeyboardWatcher(findViewById(Window.ID_ANDROID_CONTENT));
        keyboardWatcher.addSoftKeyboardStateListener(this);
        mBinding.personInformationBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TimePickUtil.pickDate(mContext,mBinding.personInformationBirthday);
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CAMERA_RESULT:
                if (resultCode == RESULT_OK && null != data) {
                    String sdState = Environment.getExternalStorageState();
                    if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                        return;
                    }
                    String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    File file = new File("/sdcard/yookey/photo/");
                    if (!file.isDirectory()) {
                        file.mkdirs();
                    }
                    String filename = file.getPath() + "/" + name;
                    FileOutputStream fout = null;
                    try {
                        fout = new FileOutputStream(filename);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fout.flush();
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    startPhotoZoom(Uri.fromFile(new File(filename)));
                }
                break;
            case PHOTO_RESULT:
                if (resultCode == RESULT_OK && null != data) {
                    Uri u = data.getData();
                    if (u.getScheme().equals("content")) {
                        String[] project = new String[]{MediaStore.Images.Media.DATA};
                        Cursor c = getContentResolver().query(u, project, null, null, null);
                        if (c != null && c.moveToFirst()) {
                            //获取路径
                            String path = c.getString(c.getColumnIndex(project[0]));
                            startPhotoZoom(Uri.fromFile(new File(path)));
                        }
                    } else {
                        startPhotoZoom(data.getData());
                    }
                }
                break;
            case PHOTO_CUT:
                if (resultCode == RESULT_OK && null != data) {
                    Bitmap bmp = data.getExtras().getParcelable("data");
                    mBinding.personInformationCamares.setImageBitmap(bmp);
                }
                break;
        }
    }

    //裁剪图片
    private void startPhotoZoom(Uri uri) {
        if (uri == null){
            Log.i("PersonCenterActivity","the uri is null...");
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CUT);
    }

    @Override
    public void onSoftKeyboardOpened(int keyboardSize) {
        int[] location = new int[2];
        mBinding.llBody.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        int bottom = BaseApp.SCREEN_HEIGHT - (y +  mBinding.llBody.getHeight());
        if (keyboardSize > bottom) {
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat( mBinding.llBody, "translationY", 0.0f, -(keyboardSize - bottom));
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
            mAnimatorTranslateY.start();
            AnimUtil.zoomIn(mBinding.personInformationCamares, keyboardSize - bottom, scale);
        }
    }

    @Override
    public void onSoftKeyboardClosed() {
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mBinding.llBody, "translationY", mBinding.llBody.getTranslationY(), 0);
        mAnimatorTranslateY.setDuration(300);
        mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
        mAnimatorTranslateY.start();
        AnimUtil.zoomOut(mBinding.personInformationCamares, scale);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        keyboardWatcher.removeSoftKeyboardStateListener(this);
    }
}
